﻿#include <iostream>
#include <sqlite3.h>

int main(int argc, char *argv[])
{
    sqlite3* DB;
    // 打开或创建数据库文件
    int exit = sqlite3_open("example.db", &DB);

    if (exit) {
        std::cerr << "Error open DB " << sqlite3_errmsg(DB) << "\n";
        return (0);
    } else {
        std::cout << "Opened Database Successfully!" << "\n";
    }

    // 创建表
    char* errorMessage;
    const char* createSQL = "CREATE TABLE IF NOT EXISTS PERSON("
                            "ID INTEGER PRIMARY KEY AUTOINCREMENT, "
                            "NAME TEXT NOT NULL, "
                            "AGE INT);";

    exit = sqlite3_exec(DB, createSQL, nullptr, nullptr, &errorMessage);

    if (exit != SQLITE_OK) {
        std::cerr << "Error CREATE Table: " << errorMessage << "\n";
        sqlite3_free(errorMessage);
    } else {
        std::cout << "Table created successfully" << "\n";
    }

    // 插入数据
    const char* insertSQL = "INSERT INTO PERSON (NAME, AGE) VALUES ('Alice', 30);"
                            "INSERT INTO PERSON (NAME, AGE) VALUES ('Bob', 25);";

    exit = sqlite3_exec(DB, insertSQL, nullptr, nullptr, &errorMessage);

    if (exit != SQLITE_OK) {
        std::cerr << "Error INSERT: " << errorMessage << "\n";
        sqlite3_free(errorMessage);
    } else {
        std::cout << "Records created successfully" << "\n";
    }

    // 查询数据
    sqlite3_stmt* stmt;
    const char* selectSQL = "SELECT ID, NAME, AGE FROM PERSON;";
    exit = sqlite3_prepare_v2(DB, selectSQL, -1, &stmt, nullptr);

    while (sqlite3_step(stmt) == SQLITE_ROW) {
        int id = sqlite3_column_int(stmt, 0);
        const unsigned char* name = sqlite3_column_text(stmt, 1);
        int age = sqlite3_column_int(stmt, 2);

        std::cout << "ID = " << id << ", Name = " << name << ", Age = " << age << "\n";
    }

    sqlite3_finalize(stmt);

    // 关闭数据库连接
    sqlite3_close(DB);
    return 0;
}
